#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <asm-generic/socket.h>

#define PORT 8080
#define BUFFER_SIZE 1024

int main() {
    int server_fd, new_socket;
    struct sockaddr_in address;
    int opt = 1;
    int addrlen = sizeof(address);
    char buffer[BUFFER_SIZE] = {0};
    char *hello = "Hello from server";
    char *confirm = "Message received";

    // 创建套接字文件描述符
    if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
        perror("套接字创建失败");
        exit(EXIT_FAILURE);
    }

    // 强制绑定套接字到端口
    if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt))) {
        perror("设置套接字选项失败");
        exit(EXIT_FAILURE);
    }
    address.sin_family = AF_INET;
    address.sin_addr.s_addr = INADDR_ANY;
    address.sin_port = htons(PORT);

    // 绑定套接字到端口
    if (bind(server_fd, (struct sockaddr *)&address, sizeof(address))<0) {
        perror("绑定失败");
        exit(EXIT_FAILURE);
    }
    // 监听连接请求
    if (listen(server_fd, 3) < 0) {
        perror("监听失败");
        exit(EXIT_FAILURE);
    }

    printf("服务器正在监听...\n");

    // 接受客户端连接
    if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addrlen))<0) {
        perror("接受连接失败");
        exit(EXIT_FAILURE);
    }

    printf("客户端已连接\n");

    while(1) {
        memset(buffer, 0, BUFFER_SIZE);
        // 读取客户端消息
        if (read(new_socket, buffer, BUFFER_SIZE) <= 0) {
            printf("客户端已断开连接\n");
            break;
        }
        printf("客户端: %s\n", buffer);
        printf("服务器: ");
        fgets(buffer, BUFFER_SIZE, stdin);
        // 发送确认消息给客户端
        send(new_socket, confirm, strlen(confirm), 0);
    }
    // 关闭套接字
    close(new_socket);
    close(server_fd);
    return 0;
}
